package gu.sql2java.manager.store;

import static com.google.common.base.Preconditions.checkArgument;
import java.io.IOException;
import java.net.URL;

import gu.sql2java.BaseBean;
import gu.sql2java.exception.RuntimeDaoException;

/**
 * URLStore implementation for Store table only<br>
 * CHAR(32) required for primary key type 
 * @author guyadong
 *
 */
public class BinaryStoreTable extends BaseColumnStore {

	/**
	 * 构造方法<br>
	 * @param tablename 表名
	 * @param storeColumn 存储数据的字段名
	 * @param extensionColumn 存储扩展名的字段名(可为{@code null})
	 * @param mimeColumn 存储MIME类型的字段名(可为{@code null})
	 * @throws IllegalArgumentException 参数错误
	 */
	public BinaryStoreTable(String tablename, String storeColumn, String extensionColumn, String mimeColumn) throws IllegalArgumentException {
		super(tablename, storeColumn, extensionColumn, mimeColumn);

		checkArgument(metaData.primaryKeyCount == 1 && String.class.equals(metaData.primaryKeyTypes[0]),
				"String type required for primary key of %s",tablename);
		checkArgument(metaData.columnSizes[metaData.primaryKeyIds[0]] == 32,
				"size 32 required for %s.%s",tablename,metaData.primaryKeyNames[0]);

	}

	@Override
	protected URL doStore(byte[] binary, String md5, String extension, boolean overwrite, boolean makeURLOnly) throws IOException {
		try{
			BaseBean bean = manager.loadByPrimaryKey(md5);
			if(bean == null){
				bean = manager.createBean();
				bean.setValue(metaData.primaryKeyIds[0], md5);
			}
			fillStoreBean(bean,binary,extension);
			if(!makeURLOnly){
				manager.save(bean);
			}		
			return makeURL(extension, md5);
		}catch ( RuntimeDaoException e) {
			throw new IOException(e);
		}
	}
	
	@Override
	protected URL doFind(String md5) {
		BaseBean bean = manager.loadByPrimaryKey(md5);
		return bean == null ? null : makeURL(getExtension(bean), bean.primaryValues());
	}

	@Override
	protected boolean doExists(URL storedURL) {
		DatabaseURLConnection connection = new DatabaseURLConnection(storedURL).parse();
		return manager.existsPrimaryKey(connection.primaryKeys);
	}
	@Override
	protected Object[] primaryKeysOf(String md5, String extension){
		return new Object[]{md5};
	}

}
